//
//  ZMCategoryViewController.swift
//  LoveBeen
//
//  Created by pg on 2017/8/6.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit
import SVProgressHUD

var gl_selectedProductArray: [ZMProductsModel] = [ZMProductsModel]()


class ZMCategoryViewController: ZMBaseController ,CAAnimationDelegate{
         
     var categoryModelArray : [ZMCategoriesModel]?
    
    //数组属性.记录用户选择的所有的商品模型
//    var selectedProductModelArray:[ZMProductsModel] = [ZMProductsModel](){
//        didSet{
        //FIXME: 打印输出
//            print("选中模型发生改变")
//            for model in selectedProductModelArray {
//                
//                print(model.name! + ":" + model.id!)
//            }
//           //将商品id相同的模型  合并为一个模型
//            var tempArray: [ZMProductsModel] = [ZMProductsModel]()
//            for (i,model) in selectedProductModelArray.enumerated(){
//                
//                for index in (i+1) ..< selectedProductModelArray.count{
//                    let indexmodel = selectedProductModelArray[index]
//                    if model.id == indexmodel.id{
//                        model.buyNum += indexmodel.buyNum
//                    }
//                }
//                tempArray.append(model)
//            }
//            //删除所有具有相同id的模型
//            for temp in tempArray{
//                
//                for (_,model) in selectedProductModelArray.enumerated(){
//                    if temp.id == model.id{
//                        selectedProductModelArray.remove(at: selectedProductModelArray.index(of: model)!)
//                      
//                    }
//                }
//            }
//     
//            //将更新后的模型添加到选中商品数组中
//            selectedProductModelArray.append(contentsOf: tempArray)
//            for model in selectedProductModelArray {
//                
//                print(model.name! + ":" + model.id!)
//            }
            
            //刷新数据
     //       self.rightBottonTableView.reloadData()
//        }
//        
//    }
    
    //MARK:- 懒加载左侧tableview
    fileprivate lazy var leftTabelView : ZMLeftTableView = {
       let tableview = ZMLeftTableView(frame: CGRect.zero, style: UITableViewStyle.plain)
        
        return tableview
    }()
    
    //MARK:- 添加右下方的tableview
    fileprivate lazy var rightBottonTableView : ZMRightTableView = {
       let tableview = ZMRightTableView(frame: CGRect.zero, style: UITableViewStyle.plain)
        
        
       return tableview
    }()
    
    
    //MARK:- 懒加载右侧上方的collectionview
    
    fileprivate lazy var rightTopCollectionView : ZMCollectionView = {
        let collection = ZMCollectionView()
        
        collection.titleArray = ["全部分类","饮用水","酒类","碳酸饮料","功能饮料"]
        
      //  collection.isScrollEnabled = false
        
        return collection
    }()
    override func viewDidLoad() {
        super.viewDidLoad()

        print("创建分类视图")
        
        //关闭毛玻璃效果
        self.navigationController?.navigationBar.isTranslucent = true
     
        //添加做出tableview
        view.addSubview(leftTabelView)
        leftTabelView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(64)
            make.bottom.leading.equalTo(view)
            make.width.equalTo(100)
        }
        
        //添加右侧上方的collectionview
        view.addSubview(rightTopCollectionView)
        rightTopCollectionView.snp.makeConstraints { (make) in
            make.top.equalTo(leftTabelView)
            make.trailing.equalTo(view)
            make.leading.equalTo(leftTabelView.snp.trailing)
        
            //给定的临时值,在collectionview中需要动态计算collecitonview的高度
            make.height.equalTo(80).priority(.high)
        }
        //添加右下方的tableview
       view.addSubview(rightBottonTableView)
        rightBottonTableView.snp.makeConstraints { (make) in
            make.top.equalTo(rightTopCollectionView.snp.bottom)
            make.trailing.bottom.equalTo(view)
            make.leading.equalTo(rightTopCollectionView)
        }
        //leftTableView初始化操作
        setupLeftTableView()
        
        //MARK:- rightBottonTableView初始化操作
        rightBottonTableView_init()
        
        //MARK:- rightTopCollectionView初始化操作
        rightTopCollectionView_init()
        
        ////加载网络数据
        loadCategoyyWebData()
        //导航条添加搜索按钮
        addSearchNavItem()
        
      
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(addToShoppingCarViewButtonClick(info:)), name: NSNotification.Name(AddToShoppingCarViewNotification), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(subFromShoppingCarViewButtonClick(info:)), name: NSNotification.Name(SubFromShoppingCarViewNotification), object: nil)
        
        //注册通知监听商品显示cell的点击事件
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectCellInRightTableView(info:)), name: NSNotification.Name(ShowProductCellDidSelectedNotification), object: nil)
        
    }
    
    
    
    
    //MARK:- 右侧tableview中商品展示cell点击事件
    func didSelectCellInRightTableView(info: NSNotification){
    
        
        //获取点击cell的model
      //  let model = info.userInfo!["model"] as! ZMProductsModel
        
        let index = info.userInfo!["indexpath"] as! IndexPath
        let model = self.categoryModelArray![index.section].produceModels![index.row]
        
        let productViewVC = ZMProductViewController()
        productViewVC.productModel = model
        productViewVC.selectedProductModelArr = gl_selectedProductArray
        
        productViewVC.hidesBottomBarWhenPushed = true
        
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
        
        self.navigationController?.pushViewController(productViewVC, animated: true)
        
    }
    
    
    //MARK:-  右侧cell中的 + 按钮单击事件监听 通知方法
    func addToShoppingCarViewButtonClick(info:Notification){
        
        //获取点击cell对应的model
        var selectedCellModel = info.userInfo!["model"] as! ZMProductsModel
       //  print("新: \(selectedCellModel.buyNum)")
       //将发送的模型转成当前控制器创建的模型
        var isExist: Bool = false
        for categoryModel in self.categoryModelArray!{
            
            for model in categoryModel.produceModels!{
                
                if model.id == selectedCellModel.id{
                    model.buyNum += 1
                    selectedCellModel = model
                    isExist = true
                    break
                }
           }
            
        }
        if isExist == false{
            //获取商品的分类id
            let categoryID = selectedCellModel.category_id
            for categoryModel in self.categoryModelArray!{
                if categoryModel.id == categoryID{
                    categoryModel.produceModels?.append(selectedCellModel)
                }
            }
        }
        
        //同一个商品只需要保存一个模型就可以了  不能重复
        if gl_selectedProductArray.contains(selectedCellModel) == false{
            gl_selectedProductArray.append(selectedCellModel)
        }
        
        self.rightBottonTableView.reloadData()
        
        //获取动画中心点坐标
        guard let pointed = info.userInfo?["point"] else {
            NotificationCenter.default.post(name: NSNotification.Name(TabBatRedViewCountChangedNotification), object: gl_selectedProductArray)
            
            return
        }
        let  point = pointed as! CGPoint
        //获取需要做动画的图片
        let image = info.userInfo!["image"] as! UIImage
        
        //创建动画view
        let imageView = UIImageView(image: image)
        imageView.center = point
        keywindow!.addSubview(imageView)
        
        
        imageView.destruct()
        //发送通知给tabBar,显示购物车商品数量
        NotificationCenter.default.post(name: NSNotification.Name(TabBatRedViewCountChangedNotification), object: gl_selectedProductArray)
        
 
        
    }
    
     
    //MARK:- 右侧cell中的 - 按钮单击事件监听 通知方法
    func subFromShoppingCarViewButtonClick(info:Notification){
        //获取点击cell对应的model
        var selectedCellModel = info.userInfo!["model"] as! ZMProductsModel
        for categoryModel in self.categoryModelArray!{
            
            for model in categoryModel.produceModels!{
                
                if model.id == selectedCellModel.id{
                    model.buyNum -= 1
                    selectedCellModel = model
                    break
                }
          }
            
        }
      if selectedCellModel.buyNum == 0 {
            if let index = gl_selectedProductArray.index(of: selectedCellModel){
            
                gl_selectedProductArray.remove(at: index)
            }
        }
        self.rightBottonTableView.reloadData()
        //发送通知给tabBar,显示购物车商品数量
        NotificationCenter.default.post(name: NSNotification.Name(TabBatRedViewCountChangedNotification), object: gl_selectedProductArray)
        
    }
    
    
    //加载网络数据
    func loadCategoyyWebData(){
        
       
        
        ZMNetworkingManager.sharedManager.requestShopData { (modelArray, isSuccess) in
            
            if isSuccess{
                self.categoryModelArray = modelArray!
                
                
                
                //左边tableview赋值
                var cateGorytitleArr : [String] = [String]()
                for categorymodel in self.categoryModelArray!{
                    
                    cateGorytitleArr.append(categorymodel.name ?? "")
                    
                }
                self.leftTabelView.titleArray = cateGorytitleArr
                
               //加载右边tableview数据源
                self.rightBottonTableView.categoryModelArray = self.categoryModelArray
              //  self.rightBottonTableView.productModelArray = self.categoryModelArray?.first?.produceModels
                
                
            }
            
        }
        
        
    }
    
    //MARK:- 添加搜索按钮  导航条
    private func addSearchNavItem(){
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "icon_search"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(searchItemClick))
        
    }
   //MARK:- 导航条  搜索按钮点击事件
    func searchItemClick(){
        
        let searchVC = ZMSearchViewController()
        searchVC.selectedProductsModelArray = gl_selectedProductArray
        searchVC.hidesBottomBarWhenPushed = true
        
        self.navigationController?.pushViewController(searchVC, animated: true)
    }
    
    //MARK:- leftTableView初始化操作
    func setupLeftTableView(){
       
        leftTabelView.leftTabelViewCellDidSelected = {[unowned self] (indexpath) in
            
            
            let index = IndexPath(row: 0, section: indexpath.row)
            self.rightBottonTableView.scrollToRow(at: index, at: UITableViewScrollPosition.top, animated: true)
            
            
            
        }
        
        
    }
    //MARK:- rightBottonTableView初始化操作
    func rightBottonTableView_init(){
        
        rightBottonTableView.rightTableViewScroll = {[unowned self] (indexpath) in
            
            self.leftTabelView.selectRow(at: indexpath, animated: false, scrollPosition: UITableViewScrollPosition.none)
            
        }
    }
    //MARK:- rightTopCollectionView初始化操作
    func rightTopCollectionView_init(){
               
        rightTopCollectionView.titleArray = ["全部分类","饮用水","酒类","碳酸饮料","功能饮料"]
    }

   
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.rightBottonTableView.reloadData()
    }
   
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func setupNavWhenNotLogin() {
        super.setupNavWhenNotLogin()
        
        self.navigationController?.navigationBar.barTintColor = UIColor.white
    }

}




